package com.github.sd4324530.fastweixin.api.extra;

import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * token 刷新任务
 */
public class TokenRefreshTask implements Runnable  {

    private static final Logger LOG = LoggerFactory.getLogger(TokenRefreshTask.class);
    /**
     * token 预留15分钟的刷新时间
     */
    private final static long RESERVE_TIME = 6300L*1000;

    /**
     * 每 10分钟 检查一次
     */
    public final static long PERIOD = 600L*1000;

    private final TokenCache cache;

    public TokenRefreshTask(TokenCache cache) {
        this.cache = cache;
    }

    @Override
    public void run() {
        LOG.info("开始检查token有效性");
        for (ApiConfig apiConfig : cache.getAllApi()) {
            long now = System.currentTimeMillis();

            Token access = cache.get(apiConfig.getAppid(), TokenType.ACCESS_TOKEN);
            if(null == access){ // 初始化时
                continue;
            } else if(now - access.getUpdateTime() >= RESERVE_TIME){ // 检查时
                LOG.debug("刷新access token , appid{}",apiConfig.getAppid());
                Token temp = TokenService.getToken(apiConfig);
                access.setToken(temp.getToken());
                access.setUpdateTime(now);
            }

            LOG.debug("当前token:{},当前token已生存[{}]秒", access, (now - access.getUpdateTime()) / 1000);
            if(null != access.getToken() && access.getToken().trim().length()>0){
                cache.put(access);
            }



            now = System.currentTimeMillis();
            Token jsTicket = cache.get(apiConfig.getAppid(), TokenType.JSAPI_TICKET);
            if(null == jsTicket){ // 初始化时
                continue;
            } else if(now - jsTicket.getUpdateTime() >= RESERVE_TIME){ // 检查时
                LOG.debug("刷新jsapi ticket , appid [{}]", apiConfig.getAppid());
                Token temp = TokenService.getJSToken(access);
                jsTicket.setToken(temp.getToken());
                jsTicket.setUpdateTime(now);
            }
            LOG.debug("当前jsapi:{},当前jsapi已生存[{}]秒", jsTicket, (now - jsTicket.getUpdateTime()) / 1000);
            if(null != jsTicket.getToken() && jsTicket.getToken().trim().length()>0){
                cache.put(jsTicket);
            }
        }
    }
}
